/*
* @file investmentAnalysis/ClosedPositionList.js
* 复盘分析/平仓列表
*/
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { Table, DatePicker, Button, Radio } from 'antd';
import moment from 'moment';
import _ from 'lodash';

import cols from './closedPositionsColumns';
import CloseOrderDetail from './CloseOrderDetail';

import './closedPositionList.less';

const RangePicker = DatePicker.RangePicker;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;

const columns = cols.map((item) => {
	item.sorter = true;
	return item;
});

const datePickerButtons = [
	"三天内", 
	"一周内", 
	"一个月内", 
	"全部"
	]

const mapStateToProps = state => ({
	list: state.closedPositions.list,
	page: state.closedPositions.page,
	selected: state.closedPositions.selected,
	selectedTrader: state.featureList.selectedTrader,
	currentDataDate: state.featureList.currentDataDate,
});

const mapDispatchToProps = {
	getClosedPositions: query => ({
		type: 'closedPositions/getClosedPositions',
		payload: query || {},
	}),
};

@connect(mapStateToProps, mapDispatchToProps)
export default class ClosedPositionsList extends Component {
	static propTypes = {
		list: PropTypes.array.isRequired,
		page: PropTypes.object,
		selectedTrader: PropTypes.object,
		currentDataDate: PropTypes.any,
	}
	state = {
		pagination: { currentpage: 1, pagesize: 10 },
		selectedDateValue: [moment(this.props.currentDataDate).add(-2, 'days'), moment(this.props.currentDataDate)],
		selectedDateRgValue: datePickerButtons[0],
		isOnDatePicker: false,
		expandedRowKeys: [],
	}
	componentDidMount() {
		if (this.props.selectedTrader != null && this.props.currentDataDate != null) {
			this.getData(this.props);
		}
	}
	componentWillReceiveProps(nextProps) {
		if (nextProps !== this.props && nextProps.selectedTrader !== this.props.selectedTrader) {
			this.setState({ selectedDateValue: [moment(nextProps.currentDataDate).add(-2, 'days'), moment(nextProps.currentDataDate)] }, () => {
				this.getData(nextProps);
			});
		}
	}
	getData({ getClosedPositions, selectedTrader }, other = {}) {
		const { trader } = selectedTrader;
		const { pagination, selectedDateValue } = this.state;
		
		const query = { trader, ...pagination, ...other };
		if (_.isArray(selectedDateValue) && selectedDateValue.length == 2) {
			query.begindate = selectedDateValue[0].format('YYYY-MM-DD');
			query.enddate = selectedDateValue[1].format('YYYY-MM-DD');
		} else {
			query.begindate = '';
			query.enddate = '';
		}
		getClosedPositions(query);
	}
	handleTableChange = (pagination, filters, sorter) => {
		const pager = { ...this.state.pagination };
		pager.currentpage = pagination.current;

		const query = {
			...pager,
			trader: this.props.selectedTrader.trader,
		};

		if (sorter.columnKey) {
			query.sortField = sorter.columnKey;
			query.sortOrder = sorter.order;
		}

		this.setState({
			pagination: pager,
		}, () => {
			this.getData(this.props, query);
		});
	}
	selectedDateRgOnChange = (e) => {
		const { currentDataDate } = this.props;
		let selectedDateValue;
		if (e.target.value === '三天内') {
			selectedDateValue = [moment(currentDataDate).add(-2, 'days'), moment(currentDataDate)];
		}
		if (e.target.value === '一周内') {
			selectedDateValue = [moment(currentDataDate).add(-6, 'days'), moment(currentDataDate)];
		}
		if (e.target.value === '一个月内') {
			selectedDateValue = [moment(currentDataDate).add(-30, 'days'), moment(currentDataDate)];
		}
		if (e.target.value === '全部') {
			selectedDateValue = [];
		}
		
		const pagination = { ...this.state.pagination, current: 1 };
		this.setState({ pagination, selectedDateValue, selectedDateRgValue: e.target.value, }, () => {
			this.getData(this.props);
		});
	}
	handleDateOnChange = (dates, dateStrings) => {
		const pagination = { ...this.state.pagination, current: 1 };
		this.setState({ pagination, selectedDateRgValue: null, selectedDateValue: dates }, () => {
			this.getData(this.props);
		});
	}
	handleOnExpandClick = (expanded, record) => {
		const rowKey = record.closeOrderId + record.openOrderId;
		this.handleExpand(rowKey)
	}
	handleOnRowClick = (record, index, event) => {
		const rowKey = record.closeOrderId + record.openOrderId;
		this.handleExpand(rowKey)
	}
	handleExpand = (rowKey) => {
		let expandedRowKeys = this.state.expandedRowKeys;
		const rowKeyIndex = _.findIndex(expandedRowKeys, function(val) {
			return val == rowKey
		})
		if (rowKeyIndex == -1) {
			expandedRowKeys.push(rowKey)
		} else {
			if (expandedRowKeys.length == 1) {
				expandedRowKeys = []
			} else {
				expandedRowKeys.splice(rowKeyIndex, 1);
			}
		}
		this.setState({ expandedRowKeys })
	}

	render() {
		const { list, page: { totalnum }, currentDataDate } = this.props;
		const { pagination: { currentpage, pagesize }, expandedRowKeys } = this.state;
		const pager = { current: currentpage, pageSize: pagesize, total: totalnum };
		return (
			<div className="closedPositionList">
				<div style={{ padding: '10px 0' }}>
					{currentDataDate &&
						<RangePicker
							value={this.state.selectedDateValue}
							defaultValue={[moment(currentDataDate).add(-2, 'days'), moment(currentDataDate)]}
							ranges={{
								'三天内': [moment(currentDataDate).add(-2, 'days'), moment(currentDataDate)],
								'一周内': [moment(currentDataDate).add(-6, 'days'), moment(currentDataDate)],
								'一个月内': [moment(currentDataDate).add(-30, 'days'), moment(currentDataDate)],
								'全部': [],
							}}
							onChange={this.handleDateOnChange}
						/>}
					<RadioGroup style={{marginLeft: 20}} value={this.state.selectedDateRgValue} defaultValue={datePickerButtons[0]} onChange={this.selectedDateRgOnChange}>
					{datePickerButtons.map((value, index) => <RadioButton value={value}>{value}</RadioButton>)}
					</RadioGroup>
				</div>

				<Table
					size="small"
					rowKey={row => (row.closeOrderId + row.openOrderId)}
					dataSource={list}
					columns={columns}
					pagination={pager}
					onChange={this.handleTableChange}
					expandedRowKeys={expandedRowKeys}
					expandedRowRender={row => (<div className="expendedItem"><CloseOrderDetail detail={row} /></div>)}
					onRowClick={this.handleOnRowClick}
					onExpand={this.handleOnExpandClick}
				/>
			</div>
		);
	}
}

